package org.ucas.faker.web.utils.wx;

import org.ucas.faker.web.utils.model.RawPatent;
import org.ucas.faker.web.dto.PageDto;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class WxPage {

  private WxClient client;

  private Integer pageNumber;

  private String query;

  private Integer totalPage;

  private List<String> toFetch;

  private List<Long> successed;

  private Set<String> excluded;

  public WxPage(WxClient client) {
    this.client = client;
  }

  public WxPage(WxClient client, String query, Integer pageNumber) {
    this.client = client;
    this.pageNumber = pageNumber;
    this.query = query;
  }

  public void fetchMeta() {
    PageDto<RawPatent> page = null;
    try {
      page = client.search(query,pageNumber);
    } catch (UnsupportedEncodingException e) {
      toFetch = null;
      totalPage = null;
      return;
    }
    if(page == null) return;
    totalPage = page.totalPages;
    toFetch = page.entries.stream().map(p->p.sourceId).filter(id->{
      return excluded == null || !excluded.contains(id);
    }).collect(Collectors.toList());


  }

  public void fetchData() {
    if(toFetch == null || toFetch.size() == 0) return;
    List<String> failed = new ArrayList<>();
    List<Long> got = new ArrayList<>();
    for(String id:toFetch) {
      RawPatent patent = client.detail(id);
      if(patent == null) {
        failed.add(id);
        continue;
      }
      try {
        client.patentService.create(patent);
        got.add(patent.id);
      } catch (Exception e) {
        e.printStackTrace();
        failed.add(id);
      }

    }
    if(successed == null) successed = got;
    else successed.addAll(got);

    toFetch = failed;
  }

  public boolean done() {
    return toFetch != null && toFetch.size() == 0;
  }

  public void sync() {
    if(toFetch == null) fetchMeta();
    fetchData();
  }

  public WxClient getClient() {
    return client;
  }

  public void setClient(WxClient client) {
    this.client = client;
  }

  public Integer getPageNumber() {
    return pageNumber;
  }

  public void setPageNumber(Integer pageNumber) {
    this.pageNumber = pageNumber;
  }

  public String getQuery() {
    return query;
  }

  public void setQuery(String query) {
    this.query = query;
  }

  public Integer getTotalPage() {
    return totalPage;
  }

  public void setTotalPage(Integer totalPage) {
    this.totalPage = totalPage;
  }

  public List<String> getToFetch() {
    return toFetch;
  }

  public void setToFetch(List<String> toFetch) {
    this.toFetch = toFetch;
  }

  public List<Long> getSuccessed() {
    return successed;
  }

  public void setSuccessed(List<Long> successed) {
    this.successed = successed;
  }

  public WxPage exclude(Set<String> excluded) {
    this.excluded = excluded;
    return this;
  }
}
